package com.mazaiting.sms.listeners;

import com.mazaiting.rabbitmq.executor.IMessageExecutor;
import com.mazaiting.sms.constant.SmsConstant;
import com.mazaiting.sms.domain.dto.SmsDto;
import com.mazaiting.sms.factory.ServiceFactory;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 短信 MQ 监听
 * RabbitListener 可以自动创建队列, 交换机
 * 但需要将当前类交给 Spring 管理
 * @author mazaiting
 * @create_time 2022/3/28 19:23
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SmsListener {

    private final IMessageExecutor messageExecutor;

    private final ServiceFactory serviceFactory;

    /**
     * 消息监听
     * 监听时使用 DL 开始的前缀
     */
    @RabbitListener(
            containerFactory = "retryRabbitListenerContainerFactory",
            bindings = @QueueBinding(
                    value = @Queue(SmsConstant.QUEUE_SMS_LOGIN_DELAY),
                    exchange = @Exchange(value = SmsConstant.EXCHANGE_SMS_LOGIN_DELAY),
                    key = SmsConstant.KEY_SMS_LOGIN_DELAY
            )
    )
    public void receiveSms(Message message, Channel channel) {
        messageExecutor.execute(message, channel, SmsDto.class, smsDto -> serviceFactory.smsService().send(smsDto));
    }
}
